<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class CommodityAttr extends Model
{

    protected $table = 'commodity_attr';

    protected $fillable = [
        'attr_value', 'pick_code','stock_num',
    ];

    public function commodity()
    {
        return $this->belongsTo(Commodity::class, 'commodity_id', 'id');
    }

    public function rentcloth()
    {
        return $this->hasOne(RentCloth::class, 'commodity_attr_id', 'id');
    }

    public function brand()
    {
        return $this->hasOneThrough(
            Brand::class,
            Commodity::class,
            'brand_id', // 中间模型外键
            'id', // 表外键
            'commodity_id', // 本地键
            'id' // 中间模型本地键
        );
    }
    public function commodityType()
    {
        return $this->hasOneThrough(
            CommodityType::class,
            Commodity::class,
            'commodity_type', // 中间模型外键
            'id', // 表外键
            'commodity_id', // 本地键
            'id' // 中间模型本地键
        );
    }


    public function decrementStockNum(int $commodity_attr_id)
    {

        DB::beginTransaction();

        $res=CommodityAttr::where('id','=',$commodity_attr_id)->decrement('stock_num',1);

        $data=CommodityAttr::where('id','=',$commodity_attr_id)->get(['stock_num'])->toArray();

        if($data[0]['stock_num']<0){

            DB::rollBack();

            return '库存不足';

        }else{

            DB::commit();

            $commodity_data=CommodityAttr::find($commodity_attr_id)->commodity;

            // TODO 减少算力

            //updateComputingPower('rentClothes', $user,  $commodity_data['power_price'],'decrement');

            return 'success';
        }





    }
}
